home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10900 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: edmr70.ccinet.ab.ca!user
  2. From: d_martin@biomira.com (Douglas Martin)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Newbie needs help w/ recursion
  5. Date: 20 Mar 1996 18:41:02 GMT
  6. Organization: Biomira Inc.
  7. Message-ID: <d_martin-2003961146130001@edmr70.ccinet.ab.ca>
  8. References: <4ikq6p$io1@impsets.dash.com>
  9. NNTP-Posting-Host: edmr70.ccinet.ab.ca
  10.  
  11. In article <4ikq6p$io1@impsets.dash.com>, Jim Bosshardt <jbossha@dash.com>
  12. wrote:
  13.  
  14. > Hi, I am new and am about to pull my hair out over the supposedly simple 
  15. > recursion problem I have. The function is to take a number and raise it 
  16. > to a neg or pos power and return the value to main().  I need to take 
  17. > the following and make it a recursive function...
  18. > double power (double a, float b)
  19. > {
  20. >                         double power = 1;
  21.                           ^^^^^^^^^^^^^^^^^ 
  22. Huh?! You don't want to declare power to be a local variable if you are
  23. going to call it! Leave this out entirely.
  24.  
  25. >                         int i;
  26. >         
  27. >                         if (a == 0)
  28. >        pow = 0;
  29. >                         else if (b == 0)
  30. >        pow = 1;
  31. >    else if Ib > 0)
  32.              ^^ Did you mean to have b rather than lb here?
  33. >    {
  34. >               for(i = 1; i <= b; i++)
  35. >            pow *= a;
  36. >    }
  37. >    else if (b < 0)
  38. >    {
  39. >        b = -b;
  40. >        for (i = 1; i <= b; i+)
  41. >             pow *= a;
  42. >        return 1/pow;
  43. >     }
  44. >     return pow;
  45. > }
  46.  
  47. Remember, if power is to be recursive, you must call power somewhere
  48. within power. 
  49.  
  50. Judging from your code, you also want b to be declared an int, not a float
  51. - note what happens in your code if you, for instance, say
  52. y:=power(2.0,2.5);
  53.  
  54. Now, let's just consider positive integer exponents and leave the rest as
  55. an exercise.
  56.  
  57.  
  58. x to the power 0 is 1
  59. if n is greater than 0
  60.   x to the power n is x times (x to the power (n-1))
  61.  
  62. Now, translate that to C, add some stuff for negative exponents, and you're off.
  63.  
  64. -- 
  65. Douglas Martin                 d_martin@biomira.com
  66. Clinical Support Programmer    dmartin@freenet.edmonton.ab.ca
  67. Biomira Inc.
  68. 2011 - 94 St. Edmonton
  69.